package com.qlslylq.ad.sdk.net;

import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.qlslylq.ad.sdk.BuildConfig;
import com.qlslylq.ad.sdk.application.AdMergeSDKApp;
import com.qlslylq.ad.sdk.constant.AppConst;
import com.qlslylq.ad.sdk.constant.HttpKeyConst;
import com.qlslylq.ad.sdk.constant.UrlConst;
import com.qlslylq.ad.sdk.method.AppMethod;
import com.qlslylq.ad.sdk.net.api.ApiService;

import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * created by qlslylq <br/>
 * on 2022 <br/>
 * 网络请求<br/>
 */
public class Api {

    //连接超时(秒)
    private final static int TIME_OUT_CONN = 15;

    private static ApiService mService;

    //需要Token的Service
    public static ApiService getService() {
        if (mService == null) {
            synchronized (Api.class) {
                if (mService == null) {
                    Interceptor headInterceptor = chain -> {
                        Request newRequest = chain.request()
                                .newBuilder()
                                .header(HttpKeyConst.AUTH, HttpKeyConst.AUTH_VALUE)
                                .header(HttpKeyConst.USER_AGENT, HttpKeyConst.USER_AGENT_VALUE)
                                .header(HttpKeyConst.APP_VERSION, AppConst.SERVER_API_VERSION)
                                .header(HttpKeyConst.DEVICE_ID, AppMethod.getDeviceId())
                                .build();
                        return chain.proceed(newRequest);
                    };

                    OkHttpClient.Builder builder = new OkHttpClient.Builder();
                    builder.retryOnConnectionFailure(true)
                            .connectTimeout(TIME_OUT_CONN, TimeUnit.SECONDS)
                            .addNetworkInterceptor(headInterceptor);

                    //设置chrome调试
                    if (BuildConfig.DEBUG) {
//                        builder.addInterceptor(new LoggerInterceptor(null));
//                        builder.addNetworkInterceptor(new StethoInterceptor());
                    }

                    Retrofit retrofit = new Retrofit.Builder()
                            .baseUrl(AdMergeSDKApp.isTest() ? UrlConst.BASE_URL_DEBUG : UrlConst.BASE_URL_RELEASE)
                            .client(builder.build())
                            .addConverterFactory(GsonConverterFactory.create())
                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                            .build();

                    mService = retrofit.create(ApiService.class);
                }
            }
        }
        return mService;
    }
}
